package com.accp.hotevent.controller.admin;

import com.accp.hotevent.entity.Event;
import com.accp.hotevent.entity.Notice;
import com.accp.hotevent.entity.User;
import com.accp.hotevent.req.AddEventRequest;
import com.accp.hotevent.req.EventListRequest;
import com.accp.hotevent.resp.CommonResp;
import com.accp.hotevent.service.EventService;
import com.accp.hotevent.service.NoticeService;
import com.accp.hotevent.util.LoggedUserContext;
import com.accp.hotevent.websocket.NoticeServer;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/admin/event")
@Slf4j
public class AdminEventController {

    @Autowired
    private EventService eventService;

    @Autowired
    NoticeService noticeService;

    @Autowired
    NoticeServer noticeServer;

    @GetMapping("/one/{id}")
    public CommonResp<Event> getOne(@PathVariable("id") Integer id){
        Event event = eventService.getOne(id);
        return CommonResp.success(event);
    }

    @GetMapping("/list")
    public CommonResp<PageInfo<Event>> getlist(EventListRequest request) {
        if (request.getPageNum() == null || request.getPageNum() <= 0) {
            request.setPageNum(1);
        }
        log.info("Entering index p:{} r:{} title:{}", request.getPageNum(), request.getPageSize(), request.getTitle());
        Event event = new Event();
        if(request.getTitle() != null) {
            event.setTitle(request.getTitle());
        }
        if(request.getUserId() != null) {
            event.setUser(User.builder().id(request.getUserId()).build());
        }
        PageInfo<Event> pageInfo = eventService.list(request);
        return CommonResp.success(pageInfo);
    }

    @PutMapping("/update/approvalStatus")
    public CommonResp<Boolean> updateApprovalStatus(@RequestBody Event event){
        eventService.updateApprovalStatus(event);
        //通知
        Event eventdb = eventService.getOne(event.getId());
        Notice notice = Notice.builder()
                .userId(eventdb.getUser().getId())
                .content("<<"+event.getTitle()+">> "+event.getApprovalStatus())
                .build();
        if(event.getApprovalStatus().equals("Pending")){
            notice.setContent("<<"+eventdb.getTitle()+">> 正在审核中");
        }else if(event.getApprovalStatus().equals("Approved")){
            notice.setContent("<<"+eventdb.getTitle()+">> 已经通过了");
        }else if(event.getApprovalStatus().equals("Rejected")){
            notice.setContent("<<"+eventdb.getTitle()+">> 发表被拒绝");
        }
        noticeService.add(notice);
        noticeServer.sendInfo(notice);
        return CommonResp.success();
    }
}
